package app.models.system;

import com.ifonly.activerecord.DbUtils;
import com.ifonly.activerecord.Model;
import com.ifonly.activerecord.annotation.Table;
import com.ifonly.activerecord.sql.config.Sql;
import com.ifonly.cache.annotation.Cacheable;
import com.ifonly.cache.annotation.Cachevict;
import com.ifonly.common.ztree.simple.SimpleZNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2016-01-08 16:50
 * @since JDK 1.6
 */
@Table(name = "s_resource")
public class Resource extends Model {
    private static final long serialVersionUID = -3199208814706506864L;

    /**
     * 查询 Resource 列表
     *
     * @return SimpleZNode List for Resource
     */
    @Cacheable(name = "ResourceCache", key = "list", cacheKeyHandler = {})
    public List<SimpleZNode<Integer, Resource>> list() {
        List<SimpleZNode<Integer, Resource>> zNodes = new ArrayList<SimpleZNode<Integer, Resource>>();
        SimpleZNode<Integer, Resource> e = SimpleZNode.create(0, null, "全部资源", null);
        zNodes.add(e);

        List<Resource> resources = DbUtils.list(Resource.class, Sql.get("resource.list"));
        if (resources != null && !resources.isEmpty()) {
            for (Resource resource: resources) {
                SimpleZNode<Integer, Resource> zNode = new SimpleZNode<Integer, Resource>();
                zNode.setId(resource.getInteger("id"));
                zNode.setName(resource.getString("name"));
                zNode.setPid(resource.getInteger("pid"));
                zNode.setOpen(true);
                zNodes.add(zNode);
            }
        }
        return zNodes;
    }

    /**
     * 保存或修改 Resource 对象
     *
     * @param resource Resource对象
     */
    @Cachevict(name = {"ResourceCache", "RoleResourceCache"}, key = "list", cacheKeyHandler = {}, all = true)
    public void saveOrUpdate(Resource resource) {
        if (DbUtils.isNew(resource)) {
            resource.saveReturnGeneratedKey();
        } else {
            resource.update();
        }
    }

    /**
     * 根据 id 删除 Resource 对象
     * @param id 主键
     */
    @Cachevict(name = {"ResourceCache", "RoleResourceCache"}, key = "list", cacheKeyHandler = {}, all = true)
    public void deleteById(int id) {
        DbUtils.delete(Sql.get("resource.deleteById"), id);
    }


}
